2013-12-23 89 views

回答

4

FROM書「臨ASP.NET MVC 4第4版」:

public class CustomActionAttribute : FilterAttribute, IActionFilter { 
    public void OnActionExecuting(ActionExecutingContext filterContext) { 
     if (filterContext.HttpContext.Request.IsLocal) { 
      filterContext.Result = new HttpNotFoundResult(); 
     } 
    } 

    public void OnActionExecuted(ActionExecutedContext filterContext) { 
     // not yet implemented 
    } 
} 
+0

我敢肯定你會了解如何讓這個例子按照需要工作:) – opewix

+0

不錯的答案,雖然,我看到很多;我在返回的404 Not Found中遇到了一些麻煩。我會說'403 Forbidden'更合適。 – Stefan

+0

@Stefan有你的問題的答案:https://stackoverflow.com/questions/5649852/asp-net-web-service-i-would-like-to-return-error-403-forbidden – opewix

10

我認爲,跨域資源共享(CORS)會幫助你的,如果你有你的網站的本地URL。您可以將公開行爲的來源列表應用於您的受保護操作,並且僅限本地來源。例如:

地方:

[EnableCors(Origins = new[] { "http://localhost", "http://sample.com" })] 
public class ValuesController : ApiController 
{ 
...... 
} 

並固定:

[EnableCors(origins: "http://localhost")] 
public class ValuesController : ApiController 
{ 
...... 
} 

您可以通過在下一個鏈接瞭解更多的細節:CORS support for ASP.NET Web APIScope Rules for [EnableCors]

+0

感謝您的建議。我不會想到這樣做。 –

+0

不會阻止來自瀏覽器的呼叫嗎?服務器端的電話不會被允許,假設開放的端口和什麼? – user323774

+0

@ user323774我開發了使用我的API的移動應用程序,並且在允許啓用cors屬性之前我無法訪問我的API(EnableCorsAttribute(「*」,「*」,「*」);) – RredCat