Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

asp.net web api - owin cors or web api cors

there are 100s of question on CORS on web-api, and on how to enable CORS, there is a different answer each one provides. I am so confused and dont know which answer is correct. And the problem is none of the answers actually explains it point wise, what each line of code does, so that I can understand and solve my problem rather than copy-pasting the code.

anyways, the question is: I am using asp.net web api 2 using owin. And i need to enable CORS. how do I do it? There is cors settings for OWIN

  application.UseCors(CorsOptions.AllowAll);

and there is cors settings for asp.net web api

   var cors = new EnableCorsAttribute("*", "*", "*", "*");
   config.EnableCors(cors);

which one should I use given I am not using OAUTH (I am specifying this because answers on SO differ on when we use OAUTH v/s when we dont use it).

Do i need to enable CORS for both OWIN & WEB-API or only for one of them. There is issue if both are enabled, read here

It would be really helpful if someone can explain me the difference between

  1. OWIN CORS
  2. WEB API CORS
  3. CORS with OAUTH using OWIN/WEBAPI

Also there are answers for self-hosted web api against owin hosted web-api, which further adds to the confution :(, sorry for the rant

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are supposed to use Web API's CORS if you need CORS applied to your API Controllers. For everything else (like a token service) you're stuck with having to use Owin.Cors.

If you end up using both, you'll need to make sure they don't overlap and apply CORS twice to the same request.

Web API 2.2 makes it easy to enable CORS by providing the EnableCorsAttribute.

Basic Usage

[EnableCors("*", "*", "*")]
public class ResourcesController : ApiController
{
    ...

Attribute definition

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)]
public EnableCorsAttribute(
    string origins,
    string headers,
    string methods
)

To enable CORS globally use

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.example.com", "*", "*");
        config.EnableCors(cors);
        // ...
    }
}

You will also need to install the CORS package from nuget

Install-Package Microsoft.AspNet.WebApi.Cors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...