3 回答
TA贡献1825条经验 获得超6个赞
你的 Getting Words 类应该是这样的
public class GettingWords
{
private static HttpClient _client = new HttpClient();
public async Task<string> GettingWordAsync(string word, string adress)
{
string result;
string data = await _client.GetStringAsync(adress);
string pattern = word;
// Instantiate the regular expression object.
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
// Match the regular expression pattern against your html data.
Match m = r.Match(data);
if (m.Success)
{
result = "Word " + word + " finded in " + adress;
}
else
{
result = "Word not finded";
}
return result;
}
}
并像这样使用
私人只读 GettingWords _repository;
public HomeController(GettingWords repository){
_repository = repository;
}
[HttpPost]
public async Task<JsonResult> SearchWord([FromBody] RequestModel model){
var result = await _repository.GettingWordAsync(model.word, model.adress);
return Json(result);
}
TA贡献1799条经验 获得超8个赞
我能够通过这段代码解决异步问题
public async Task<string> GettingWordAsync(string word, string adress)
{
HttpWebRequest req = WebRequest.CreateHttp(adress);
req.Method = "GET";
req.KeepAlive = true;
string result;
string content = null;
string pattern = word;
HttpStatusCode code = HttpStatusCode.OK;
try
{
using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = await sr.ReadToEndAsync();
}
}
catch (WebException ex)
{
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = sr.ReadToEnd();
code = response.StatusCode;
}
}
// Instantiate the regular expression object.
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
// Match the regular expression pattern against your html data.
Match m = r.Match(content);
if (m.Success)
{
result = "Word " + word + " finded in " + adress;
}
else
{
result = "Word not finded";
}
return result;
}
}
- 3 回答
- 0 关注
- 200 浏览
添加回答
举报