![](/img/trans.png)
[英]how can i pass my webform value in webapi controller as a model class using jquery ajax
[英]How do I put a value from a different domain in my Model through a WebAPI Controller using CORS?
該應用程序接收來自另一個非ASP.NET Web應用程序的請求。 我已經實現了跨域資源共享,現在我需要從請求中獲取價值。
我的模特
public class User
{
public int userID { get; set;}
public string username { get; set; }
public string password { get; set;}
public int group { get; set; }
public string permission { get; set;}
}
我的控制器
[EnableCors("*", "*", "*")]
public class LoginController : ApiController
{
public User[] PutUser()
{
//this is where I want to create a user through requests to further work with the application
}
}
我該怎么辦?
我在MVC項目中實現了類似的功能,在該項目中,我從另一個域調用我們的應用程序。 為此,您需要在響應中添加帶有Origin值(請求的來源)的Access-Control-Allow-Origin標頭。 我想這種方法也適用於Web API。 您不想允許來自任何網站的請求! 此方法將允許您響應初始請求,這似乎是您要返回的用戶數組時要執行的操作。
我發現最簡單的方法是創建一個屬性,您可以使用該屬性來裝飾您的方法:
public class AllowCrossSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
switch (filterContext.RequestContext.HttpContext.Request.Headers["Origin"])
{
case "https://myotherwebsite1.com":
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", filterContext.RequestContext.HttpContext.Request.Headers["Origin"]);
break;
case "https://myotherwebsite2.com":
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", filterContext.RequestContext.HttpContext.Request.Headers["Origin"]);
break;
default:
filterContext.Result = new EmptyResult();
break;
}
base.OnActionExecuting(filterContext);
}
}
switch語句檢查源,並確保它來自受信任的源。 您無需對這些代碼進行硬編碼,但出於對話的考慮,我有。 如果您找到匹配項,則將適當的標題添加到響應中。
然后,您可以使用以下屬性裝飾您的方法:
[AllowCrossSite]
public class LoginController : ApiController
{
public User[] PutUser()
{
//this is where I want to create a user through requests to further work with the application
}
}
要從其他應用程序實際發送數據,您可以使用jquery Ajax請求或僅使用表單發布,但請確保將方法設置為PUT或POST(取決於您要執行的操作,根據命名尚不清楚)依靠動詞。
您可以在FormDataCollection中收集請求的數據,我相信:
public public User[] PutUser(FormDataCollection form)
{
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.