ASP.NET Web Api-如何在ApiController中检测请求是否来自移动设备



我公司有一个旧的Controller类,它继承了ApiController

其中一个操作是从浏览器接收数据的POST端点。

由于我在ApiController中,所以我没有要检测的内置属性IsMobile

那么,如何在ApiController中检测请求是否来自移动设备?

有其他建议吗?

您可以查看User Agent标头,并查找移动客户端的提示

var userAgent = Request.Headers.UserAgent.ToString();

您可以查找某些字符串,如"mobile"或"mobi"(或搜索多个备选关键字(。

下面是一个列出移动客户端用户代理的页面:https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/mobile/7

更新:

以下是一个库,它已经在对用户代理标头执行类似的操作:https://github.com/wangkanai/Detection

根据最初的答案,关键是使用UserAgent。我找到了这个答案,我把它封装在ActionFilter中,以防我想用它来完成多个动作

/// <summary>
/// This action filter sets Request's properties with a "BrowserCapabilitiesFactory" object. <br/>
/// To get it, use <b>Request.Properties.TryGetValue("UserBrowser", out yourObjectToSet);</b>. <br/>
/// With that, you can check browser details of the request. Use this for <b>ApiController</b> actions. <br/>
/// If browser was not found or any exception occured in filter, then the value of the key will be set to null, 
/// By doing that , ensures that the Properties will always have a key-value of UserBrowser
/// </summary>
public class GetUserBrowserActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
try
{
// ============================== Get User agent and parse it to a strongly type object ============================== //
var userAgent = HttpContext.Current.Request.UserAgent;
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
actionContext.Request.Properties.Add("UserBrowser", userBrowser);
}
catch (Exception ex)
{
actionContext.Request.Properties.Add("UserBrowser", null);
}
}
}

最新更新