如何在 C# 中无需任何身份验证即可使用 WebAp2
本文关键字:身份验证 任何 可使用 WebAp2 | 更新日期: 2023-09-27 17:56:29
Dearl All 我是 WebAPI2 的新手。我想以 JSON 格式使用函数中的数据,但抛出错误状态代码:403,原因短语:"ModSecurity Action"。 我可以直接从浏览器消费,但不能从 HttpClient 消费。未实施安全性。
在本地服务器上完美运行,但在远程共享服务器上抛出上述错误。 APIURL。http://api.owncircles.com/api/Circles/Education/Questions/getAns/2012460157
接口函数代码。
[HttpGet()]
[AllowAnonymous]
[Route("~/api/Circles/Education/Questions/getAns/{quesID}")]
public IHttpActionResult getAns(string quesID)
{
IQuestions objQuestion = Questions.getInatance();
var qtn = objQuestion.getAns(quesID);
return Json(qtn);
}
客户端
[AllowAnonymous]
public async Task<ActionResult> checkAns(string id)
{
string url = common.apiURL + "Circles/Education/Questions/getAns/"+id;
//HttpClient client = new HttpClient(new HttpClientHandler() {UseDefaultCredentials = true });
HttpClient client = new HttpClient();
// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.));
// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("");
// client.DefaultRequestHeaders.Authorization = null;
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ent_QuestionsDetails Questions = null;
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Questions = response.Content.ReadAsAsync<ent_QuestionsDetails>().Result;
}
OC.Models.mod_Questions objModel = new OC.Models.mod_Questions();
objModel.questionID = Questions.questionID;
objModel.questions = Questions.questions;
objModel.questionOptions = Questions.questionOptions;
return View(objModel);
}
似乎是您的用户代理,如果省略此选项,请求将被拒绝。如果您在标头中模仿 chrome 用户代理值,则请求将成功。这是一个独立的工作示例:
请注意,此示例不使用 await/async,因为它已在控制台应用中进行了测试
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://api.owncircles.com/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
var result = client.GetAsync("api/Circles/Education/Questions/getAns/2012460157").Result;
if(result.IsSuccessStatusCode)
Console.Write(result.Content.ReadAsStringAsync().Result);
else
Console.Write("fail");
}
话虽如此,我不知道您在用户代理上的API服务器端进行了什么样的检查,它会拒绝请求。