我希望在使用ASP.NET Web API时从客户端应用程序对用户进行身份验证。我已经看了网站上的所有视频,还阅读了this forum post。
正确放置[Authorize]
属性将返回401 Unauthorized
状态。但是,我需要知道如何允许用户登录到API。
我想从Android应用程序向API提供用户凭据,让用户登录,然后对所有后续API调用进行预身份验证。
发布于 2013-04-26 21:52:59
我以android为例。
public abstract class HttpHelper {
private final static String TAG = "HttpHelper";
private final static String API_URL = "http://your.url/api/";
private static CookieStore sCookieStore;
public static String invokePost(String action, List<NameValuePair> params) {
try {
String url = API_URL + action + "/";
Log.d(TAG, "url is" + url);
HttpPost httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(entity);
}
return invoke(httpPost);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return null;
}
public static String invokePost(String action) {
return invokePost(action, null);
}
public static String invokeGet(String action, List<NameValuePair> params) {
try {
StringBuilder sb = new StringBuilder(API_URL);
sb.append(action);
if (params != null) {
for (NameValuePair param : params) {
sb.append("?");
sb.append(param.getName());
sb.append("=");
sb.append(param.getValue());
}
}
Log.d(TAG, "url is" + sb.toString());
HttpGet httpGet = new HttpGet(sb.toString());
return invoke(httpGet);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return null;
}
public static String invokeGet(String action) {
return invokeGet(action, null);
}
private static String invoke(HttpUriRequest request)
throws ClientProtocolException, IOException {
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
// restore cookie
if (sCookieStore != null) {
httpClient.setCookieStore(sCookieStore);
}
HttpResponse response = httpClient.execute(request);
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}
result = builder.toString();
Log.d(TAG, "result is ( " + result + " )");
// store cookie
sCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
return result;
}
请注意:不能使用i.localhost。安卓设备看起来像是本地主机。ii.If在IIS中部署web API,必须打开表单身份验证。
发布于 2016-12-05 17:46:21
使用此代码和access数据库
[HttpPost]
[Route("login")]
public IHttpActionResult Login(LoginRequest request)
{
CheckModelState();
ApiResponse<LoginApiResponse> response = new ApiResponse<LoginApiResponse>();
LoginResponse user;
var count = 0;
RoleName roleName = new RoleName();
using (var authManager = InspectorBusinessFacade.GetAuthManagerInstance())
{
user = authManager.Authenticate(request);
} reponse(ok)
}
https://stackoverflow.com/questions/11014953
复制相似问题