要用 ASP.NET MVC 開發 WEB API給大家使用,前端 javascript 工程師,總是會遇到錯誤訊息 Response to preflight request doesn’t pass access control check: It does not have HTTP ok status,這是一個超常見的 CORS (Cross-Origin Resource Sharing) – 跨來源資源共用錯誤訊息,網路上很多解法,但可以用的情境都不太一樣,我這邊提供一個我覺得最簡單請快速的方法給大家。
在 App_Start/WebApiConfig.cs 的 Register function 加入以下的程式碼
config.EnableCors();
會是長成以下的程式碼
public static void Register(HttpConfiguration config)
{
// Web API 設定和服務
config.EnableCors();
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
設定 WebAPI 的CORS 權限
我們可以在 WebApi 的 Class 上面設定,也可以在 Function 上做標記,但要注意的是不能有多個 CORS 繫結,如果你在 web.config 中設定,這邊就不能再做設定,如果你在 class 等級上設定了, function 等級就不能再設定,也是因為這個原因,所以我喜歡在 function 等級設定或是 class 等級上設定,web.config 比較少去做設定,雖然他有不用修改程式碼的好處。
add_filter( 'woocommerce_get_price_html', function( $price ) {
if ( is_admin() ) return $price;
$user = wp_get_current_user();
$hide_for_roles = array( 'wholesale', 'wholesale-silver', 'wholesale-gold' );
// If one of the user roles is in the list of roles to hide for.
if ( array_intersect( $user->roles, $hide_for_roles ) ) {
return ''; // Return empty string to hide.
}
return $price; // Return original price
} );
add_filter( 'woocommerce_cart_item_price', '__return_false' );
add_filter( 'woocommerce_cart_item_subtotal', '__return_false' );
Woocommerce 如何對不同的類別中的商品做價格控制
add_filter( 'woocommerce_get_price_html', function( $price, $product ) {
if ( is_admin() ) return $price;
// Hide for these category slugs / IDs
$hide_for_categories = array( 'clothes', 'electronics' );
// Don't show price when its in one of the categories
if ( has_term( $hide_for_categories, 'product_cat', $product->get_id() ) ) {
return '';
}
return $price; // Return original price
}, 10, 2 );
add_filter( 'woocommerce_cart_item_price', '__return_false' );
add_filter( 'woocommerce_cart_item_subtotal', '__return_false' );
近期留言